package com.jochen.core.audio

import com.badlogic.gdx.Preferences
import com.badlogic.gdx.utils.TimeUtils
import com.jochen.core.assets.MusicAsset
import com.jochen.core.assets.SoundAsset

class AudioManager(
    private val audioService: AudioService,
    private val settingsPre: Preferences
    ){
    
    companion object{
        const val SETTINGS = "settings"
        const val MUSIC_VOLUME = "musicVolume"
        const val IS_OPEN_MUSIC = "isOpenMusic"
        const val SOUND_VOLUME = "soundVolume"
    }
    
    private var isOpenMusic: Boolean = settingsPre.getBoolean(IS_OPEN_MUSIC)
    private var soundTime: Long = 0L
    private var pendingMusic: MusicAsset? = null
    
    init{
        audioService.musicVolume = settingsPre.getFloat(MUSIC_VOLUME)
        audioService.soundVolume = settingsPre.getFloat(SOUND_VOLUME)
    }
    
    fun setMusicVolume(volume: Float) {
        audioService.musicVolume = volume
        settingsPre.putFloat(MUSIC_VOLUME, volume)
    }

    fun setSoundVolume(volume: Float) {
        audioService.soundVolume = volume
        settingsPre.putFloat(SOUND_VOLUME, volume)
    }

    fun setIsOpenMusic(isOpen: Boolean) {
        settingsPre.putBoolean(IS_OPEN_MUSIC, isOpen)
        isOpenMusic = isOpen
        
        if (isOpen) {
            pendingMusic?.let {
                playMusic(it)
                pendingMusic = null
            }
        } else {
            pendingMusic = audioService.stopMusic()
        }
    }

    fun playMusic(asset: MusicAsset) {
        if (isOpenMusic) {
            audioService.playMusic(asset)
        } else {
            pendingMusic = asset
        }
    }

    fun playSound(asset: SoundAsset) {
        if (isOpenMusic && TimeUtils.timeSinceMillis(soundTime) > 500L) {
            audioService.playSound(asset)
        }
    }

    fun IsOpenMusic(): Boolean = isOpenMusic
    fun getMusicVolume(): Float = settingsPre.getFloat(MUSIC_VOLUME)
    fun getSoundVolume(): Float = settingsPre.getFloat(SOUND_VOLUME)

}